package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.commons.templates.HuanXinTemplate;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.BlackListApi;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.UserLikeApi;
import com.tanhua.dubbo.api.mongo.UserLocationApi;
import com.tanhua.server.Interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TodayBestService {

    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Reference
    private UserLocationApi userLocationApi;
    @Reference
    UserLikeApi userLikeApi;
    @Reference
    FriendApi friendApi;
    @Reference
    BlackListApi blackListApi;

    //查询今日佳人
    public ResponseEntity queryTodayBest() {
        //1. 获取当前登陆的用户id
        long userId = UserHolder.getUserId();

        //2. 根据用户id查询出今日佳人， 得到就是Recommend_user
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        //为了防止当前的用户没有推荐人，给没有推荐人的用户一个默认值
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setRecommendUserId(2L);
            recommendUser.setScore(79D);
        }

        //3.根据推荐人的用户id查找推荐人的用户信息
        UserInfo userInfo = userInfoApi.findById(recommendUser.getRecommendUserId());

        //4. 把用户信息封装到todayBestVo里面
        TodayBestVo vo = new TodayBestVo();
        if (userInfo != null) {
            BeanUtils.copyProperties(userInfo, vo);
            if (userInfo.getTags() != null) {
                vo.setTags(userInfo.getTags().split(","));
            }
        }
        //设置缘分值
        vo.setFateValue(recommendUser.getScore().longValue());


        //5. 返回响应
        return ResponseEntity.ok(vo);

    }

    /**
     * 推荐朋友 (首页推荐) 查询推荐的朋友
     *
     * @param vo
     * @return
     */
    public ResponseEntity<Object> queryRecommendation(RecommendQueryVo vo) {
        //1. 得到当前登陆的用户id
        long userId = UserHolder.getUserId();
        //2. 根据userId， page, pageSize 得到推人列表分页对象  RecomendUser
        PageResult pageResult = recommendUserApi.queryRecommendation(vo.getPage(), vo.getPagesize(), userId);
        //3. 得到pageResult里面的数据  List< RecomendUser>
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageResult.getItems();
        if (recommendUserList == null || recommendUserList.size() == 0) {
            //如果该用户没有推荐人，我也给默认推荐一批
            recommendUserList = new ArrayList<>();
            for (long i = 5; i < 10; i++) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setRecommendUserId(i);
                recommendUser.setScore(80.1 + i);
                recommendUserList.add(recommendUser);
            }
        }

        //4. 遍历所有的推荐人，查询推荐人的userInfo信息，把UserInfo的信息封装到todaybestvo对象中
        List<TodayBestVo> todayBestVoList = new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {
            //查询推荐人的用户信息
            UserInfo userInfo = userInfoApi.findById(recommendUser.getRecommendUserId());
            //每一个userInfo都对应一个用户的信息也就是对应一个todayBest
            TodayBestVo todayBestVo = new TodayBestVo();

            if (userInfo != null) {
                BeanUtils.copyProperties(userInfo, todayBestVo);
                if (userInfo.getTags() != null) {
                    todayBestVo.setTags(userInfo.getTags().split(","));
                }
            }
            //设置缘分值
            todayBestVo.setFateValue(recommendUser.getScore().longValue());

            todayBestVoList.add(todayBestVo);
        }

        //5. 修改pageResult里面存储的数据
        pageResult.setItems(todayBestVoList);
        return ResponseEntity.ok(pageResult);

    }


    /**
     * 查询佳人信息
     *
     * @param recommendUserId
     * @return
     */
    public ResponseEntity<Object> queryPersonalInfo(Long recommendUserId) {
        //1. 根据recommendUserId查询用户的信息
        UserInfo userInfo = userInfoApi.findById(recommendUserId);

        //2. 把UserInfo信息封装到 TodayBestvo
        TodayBestVo todayBestVo = new TodayBestVo();
        //属性拷贝
        BeanUtils.copyProperties(userInfo, todayBestVo);
        if (userInfo.getTags() != null) {
            todayBestVo.setTags(userInfo.getTags().split(","));
        }
        //查询当前用户与推荐用户的缘分值
        long score = recommendUserApi.queryScore(UserHolder.getUserId(), recommendUserId);
        todayBestVo.setFateValue(score);
        //最终目标： TodayBestvo
        return ResponseEntity.ok(todayBestVo);

    }

    //查看陌生人问题
    public ResponseEntity<Object> strangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);
        if (question == null) {
            return ResponseEntity.ok("您有钱吗？有车吗？有房吗?");
        }
        return ResponseEntity.ok(question.getTxt());
    }

    /**
     * @param userId 接收者的id    57
     * @param reply  回复内容
     * @return
     */
    public ResponseEntity<Object> replyQuestions(Integer userId, String reply) {
        //1. 根据当前登陆者的id，查询到登陆者的用户信息
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId()); //当前登陆者的信息
        //2. 查询陌生人问题?
        Question question = questionApi.findByUserId(userId.longValue());
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userId", userInfo.getId());
        paramMap.put("nickname", userInfo.getNickname());
        paramMap.put("strangerQuestion", question.getTxt() == null ? "有房吗？有车吗？" : question.getTxt());
        paramMap.put("reply", reply);

        String msg = JSON.toJSONString(paramMap);

//        {"userId": 1 ,"nickname":"黑马小妹","strangerQuestion":"你喜欢去看蔚蓝的大海还是去爬巍峨的高山？","reply":"我喜欢秋天的落叶，夏天的泉水，冬天的雪地，只要有你一切皆可~"}
        //目标：
        huanXinTemplate.sendMsg(userId + "", msg);

        return ResponseEntity.ok(null);
    }

    //搜索附近的人
    public ResponseEntity<Object> searchNear(String gender, Long distance) {
        //1. 等到当前登陆者id
        long userId = UserHolder.getUserId();
        //2 搜索方圆n公里的人
        /**
         * 注意： searchNear的方法没法直接返回UserLocation,因为UserLocation对象里面有一个属性
         * GeoJsonPoint， GeoJsonPoint属性没有实现序列化接口。不能支持dubbo的传输。
         * dubbo的消费者与提供者传输的数据要求对象以及对象的属性都必须要实现序列化接口。
         */
        List<UserLocation> userLocationList = userLocationApi.searchNear(userId, distance);

        //3.遍历所有的附近人
        List<NearUserVo> voList = new ArrayList<>();
        if (userLocationList != null) {
            for (UserLocation userLocation : userLocationList) {
                Long uid = userLocation.getUserId();
                UserInfo userInfo = userInfoApi.findById(uid);
                //1. 排除自己
                if (userInfo.getId() == userId) {
                    continue;
                }

                //2. 排除性别和你筛选不符合
                if (!userInfo.getGender().equalsIgnoreCase(gender)) {
                    continue;
                }
                //每一个UserInfo都对应一个NearUserVo
                NearUserVo vo = new NearUserVo();
                BeanUtils.copyProperties(userInfo, vo);
                vo.setUserId(userInfo.getId());
                voList.add(vo);
            }
        }
        return ResponseEntity.ok(voList);

    }

    public ResponseEntity<Object> cards() {
        List<TodayBestVo> voList = userInfoApi.randomRecommended(UserHolder.getUserId());
        return ResponseEntity.ok(voList);

    }

    /**
     * 当前用户添加喜欢
     *
     * @param likeId 要喜欢的id
     * @return
     */
    public ResponseEntity<Object> tanhuaLove(String likeId) {
        //创建喜欢对象
        UserLike userLike = new UserLike();
        userLike.setId(new ObjectId());
        userLike.setUserId(UserHolder.getUserId());
        userLike.setLikeUserId(Long.parseLong(likeId));
        userLike.setCreated(System.currentTimeMillis());
        //防止数据重复
        List<UserLike> isUserLike = userLikeApi.findLikeUser(UserHolder.getUserId(), likeId);
        if (isUserLike.size() > 0) {
            return ResponseEntity.ok(null);
        }
        userLikeApi.addLikeUser(userLike);

        //添加喜欢后检查对方是否也喜欢当前用户，是则添加好友
        userLikeApi.checkAndAddFriend(UserHolder.getUserId(), likeId);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity<Object> tanhuaunlove(String BlackId) {
        blackListApi.addBlacklist(UserHolder.getUserId(), BlackId);
        return null;
    }
}
